<template>
    <div>
        <Category :scene="scene"></Category>
        <el-card shadow="always" style="margin:10px 0px">
            <div v-show="scene==0">
                <el-button type="primary" size="default" :icon="Plus" :disabled="!categortStore.c3Id" @click="addSpu">
                    添加SPU</el-button>
                <el-table border stripe style="margin:10px 0px" :data="spuList.records">
                    <el-table-column label="序号" type="index" width="80px" align="center">
                    </el-table-column>
                    <el-table-column label="SPU名称" prop="spuName">
                    </el-table-column>
                    <el-table-column label="SPU描述" prop="description" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template v-slot="{row,$index}">
                            <el-button type="primary" size="small" title="添加SKU" :icon="Plus"
                             @click="addSku(row)"></el-button>
                            <el-button type="warning" size="small" title="修改SPU" :icon="Edit" @click="updateSpu(row)">
                            </el-button>
                            <el-button type="info" size="small" title="查看SKU" :icon="InfoFilled"
                                @click="showDialog(row)"></el-button>
                            <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled"
                                icon-color="yellowgreen" :title="`你确定要删除${row.spuName}`" width="300px"
                                @confirm="confirm(row)">
                                <template #reference>
                                    <el-button type="danger" size="small" title="删除SPU" :icon="Delete"></el-button>
                                </template>
                            </el-popconfirm>

                        </template>
                    </el-table-column>
                </el-table>

                <el-pagination @current-change="getSpuList" @size-change="sizeHandler"
                    v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 7]"
                    layout="prev, pager, next, jumper,->,sizes,total" prev-text="上一页" next-text="下一页"
                    :total="spuList.total" background :pager-count="7">
                </el-pagination>
            </div>
            <Spu v-show="scene==1" @changeScene="changeSceneHandler" ref="spuRef"></Spu>
            <Sku v-show="scene==2" ref="skuRef" @changeScene="changeSceneHandler"></Sku>

                 <!--展示SKU的对话框-->
      <el-dialog v-model="dialogTableVisible" title="查看SKU列表">
        <el-table :data="skuList">
          <el-table-column prop="skuName" label="名称" width="150" />
          <el-table-column property="price" label="价格" width="200" />
          <el-table-column property="weight" label="重量" />
          <el-table-column label="默认图片">
            <template #="{ row, $index }">
              <img
                :src="row.skuDefaultImg"
                alt=""
                style="width: 100px; height: 100px"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
        </el-card>

    </div>
</template>

<script setup lang="ts">
import { ref, watch, onUnmounted} from 'vue';
//引入请求函数
import { reqSpuList,reqFindSkuList ,reqDeleteSpu } from '../../../api/product/spu/spu'
//引入element-plus提供icon图标组件
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus,
    InfoFilled
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
//引入仓库
import usecategoryStore from '../../../stores/category'
//引入子组件
import Sku from './addSku.vue'
import Spu from './addOrUpdateSpu.vue'
//调用仓库数据
let categortStore = usecategoryStore();
//定义页面的切换
let scene = ref<number>(0)
//定义分页器在当前第几页
let currentPage = ref<number>(1);
//定义分页器一页显示多少内容
let pageSize = ref<number>(3)
//定义响应式对象储存服务器返回的数据
let spuList = ref({});
//储存子组件实例SPU
let spuRef = ref<any>();
//储存子组件实例SKU
let skuRef = ref<any>();
//储存sku列表
let skuList = ref([]);
//定义控制对话框显示与隐藏
let dialogTableVisible = ref<boolean>(false);
//监听三级ID变化
watch(() => categortStore.c3Id, () => {
    //三级分类的ID不能为空
    if (categortStore.c3Id == '') return;
    getSpuList();
});
//获取三级分类SPU列表请求的地方
const getSpuList = async (pager: number = 1) => {
    //整理参数
    currentPage.value = pager;
    //返回SPU列表的数据
    let result = await reqSpuList(
        currentPage.value,
        pageSize.value,
        categortStore.c3Id
    );
    //储存服务器数据
    spuList.value = result;
};
//当每一页展示数据的个数发生变化的时候，触发事件：右下角分页器下拉框
const sizeHandler = (limit: number) => {
    pageSize.value = limit;
    //再次发请求
    getSpuList();
};
//添加SPU按钮的回调
const addSpu = () => {
    //点击添加SPU按钮的时候页面切换成scene1（添加）页面
    scene.value = 1;
    //调用子组件的方法，让子组件发出两个请求
    spuRef.value.initAddSpu(categortStore.c3Id);
}
//更新SPU按钮回调
const updateSpu = (hasSpu) => {
    //点击更新SPU按钮的时候切换成scene1（添加）页面
    scene.value = 1;
    //获取子组件实例：调用子组件的方法
    spuRef.value.initHasSpuData(hasSpu);
}
//子组件SPU自定义事件回调
const changeSceneHandler = ({ scenes, flag }) => {
    //切换场景
    scene.value = scenes;
    //当前是添加
    if (flag == 'add') {
        //再次获取最新数据
        getSpuList();
    } else if (flag == 'update') {
        //当前是修改
        getSpuList(currentPage.value);
    }
};
//添加SKU按钮的回调
const addSku = (spu) => {
    //切换场景2
    scene.value = 2;
    //获取子组件实例，调用子组件方法
    skuRef.value.initSku(categortStore.c1Id, categortStore.c2Id, spu);
};


//点击第三个按钮的回调
//spu
const showDialog = async (spu) => {
  //显示对话框
  dialogTableVisible.value = true;
  //发请求获取SKU列表
  let skus = await reqFindSkuList(spu.id);
  skuList.value = skus;
};

//pop组件的确定按钮的回调
const confirm = async (spu) => {
  try {
    //删除某一个SPU
    await reqDeleteSpu(spu.id);
    //提示
    ElMessage({
      type:'success',
      message:`恭喜你删除${spu.spuName}成功`
    });
    //更新数据
    getSpuList();
  } catch (error) {
     ElMessage({
      type:'error',
      message:`恭喜你删除${spu.spuName}失败`
    });
  }
};


//当前SPU路由组件(父组件)销毁的时候，情况仓库数据
onUnmounted(() => {
  //组件销毁的时候。情况仓库里面的数据
  categortStore.c1Id = "";
  categortStore.c2Id = "";
  categortStore.c3Id = "";
  categortStore.c1List = [];
  categortStore.c2List = [];
  categortStore.c3List = [];
});
</script>

<style scoped>

</style>